package com.aizuda.encrypt.jsqlparse.visitor;

import cn.hutool.core.collection.CollUtil;
import com.aizuda.encrypt.jsqlparse.entity.JSQLCryptExpression;
import com.aizuda.encrypt.util.ParseSQLUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.FromItemVisitor;
import net.sf.jsqlparser.statement.select.LateralSubSelect;
import net.sf.jsqlparser.statement.select.ParenthesisFromItem;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.SubJoin;
import net.sf.jsqlparser.statement.select.SubSelect;
import net.sf.jsqlparser.statement.select.TableFunction;
import net.sf.jsqlparser.statement.select.ValuesList;

import java.util.List;


/**
 * 子查询
 *
 * @author nn200433
 * @date 2022-03-02 06:49:28
 */
@Slf4j
public class FromItemV extends VisitorHandle implements FromItemVisitor {

    public FromItemV(List<JSQLCryptExpression> list) {
        super(list);
    }

    @Override
    public void visit(Table tableName) {
    }

    @Override
    public void visit(SubSelect subSelect) {
        List<PlainSelect> plainSelectList = ParseSQLUtil.getPlainSelectList(subSelect.getSelectBody());
        if (CollUtil.isEmpty(plainSelectList)) {
            return;
        }
        for (PlainSelect plain : plainSelectList) {
            FromItem fromItem = plain.getFromItem();
            if (null != fromItem && fromItem.getClass().equals(SubSelect.class)) {
                fromItem.accept(new FromItemV(list));
            }
            Expression where = plain.getWhere();
            if (null != where) {
                where.accept(new ExpressionV(list));
            }
        }
    }

    @Override
    public void visit(SubJoin subjoin) {
        log.debug("---> [Mybatis SQL 解析拦截] SubJoin");
    }

    @Override
    public void visit(LateralSubSelect lateralSubSelect) {
        log.debug("---> [Mybatis SQL 解析拦截] LateralSubSelect");
    }

    @Override
    public void visit(ValuesList valuesList) {
        log.debug("---> [Mybatis SQL 解析拦截] ValuesList");
    }

    @Override
    public void visit(TableFunction tableFunction) {
        log.debug("---> [Mybatis SQL 解析拦截] TableFunction");
    }

    @Override
    public void visit(ParenthesisFromItem aThis) {
        log.debug("---> [Mybatis SQL 解析拦截] TableFunction");
    }

}
